<template>
  <div class="smart-qa-container">
    <!-- 顶部导航 - 使用BossHeader -->
    <BossHeader />

    <!-- 主要内容区域 -->
    <div class="qa-main-content">
      <!-- 左侧历史记录 -->
      <div class="qa-sidebar">
        <div class="sidebar-header">
          <h3>历史问答记录</h3>
          <el-button type="primary" size="small" @click="createNewSession">
            <el-icon><Plus /></el-icon>
            新建对话
          </el-button>
        </div>

        <!-- 历史记录列表 -->
        <div class="history-list">
          <div
            v-for="item in historyList"
            :key="item.id"
            class="history-item"
            :class="{ active: currentSessionId === item.id }"
            @click="selectHistory(item)"
          >
            <div class="history-content">
              <div class="history-question">{{ item.question }}</div>
              <div class="history-time">{{ formatTime(item.created_at) }}</div>
            </div>
            <el-icon class="delete-icon" @click.stop="deleteHistory(item.id)">
              <Delete />
            </el-icon>
          </div>

          <!-- 空状态 -->
          <div v-if="historyList.length === 0" class="empty-history">
            <el-empty description="暂无历史记录" />
          </div>
        </div>
      </div>

      <!-- 右侧对话区域 -->
      <div class="qa-chat-area">
        <!-- 对话显示区 -->
        <div class="chat-messages" ref="chatMessagesRef">
          <!-- 欢迎消息 -->
          <div v-if="messages.length === 0" class="welcome-message">
            <div class="welcome-icon">
              <el-icon :size="60"><ChatDotRound /></el-icon>
            </div>
            <h2>智能单轮问答系统</h2>
            <p>我可以回答关于IT行业、医疗行业和人事行业的问题</p>
            <div class="quick-questions">
              <div
                v-for="(q, index) in quickQuestions"
                :key="index"
                class="quick-question-item"
                @click="askQuestion(q)"
              >
                {{ q }}
              </div>
            </div>
          </div>

          <!-- 消息列表 -->
          <div v-for="(msg, index) in messages" :key="index" class="message-wrapper">
            <!-- 用户问题 -->
            <div class="message user-message">
              <div class="message-content">
                <div class="message-text">{{ msg.question }}</div>
              </div>
              <div class="message-avatar">
                <el-avatar :size="36">
                  <el-icon><User /></el-icon>
                </el-avatar>
              </div>
            </div>

            <!-- AI回答 -->
            <div class="message ai-message" v-if="msg.answer">
              <div class="message-avatar">
                <el-avatar :size="36" style="background-color: #409eff">
                  <el-icon><Cpu /></el-icon>
                </el-avatar>
              </div>
              <div class="message-content">
                <div class="message-text" v-html="formatAnswer(msg.answer)"></div>
                <div class="message-time">{{ formatTime(msg.timestamp) }}</div>
              </div>
            </div>

            <!-- 加载中状态 -->
            <div class="message ai-message" v-if="index === messages.length - 1 && isLoading">
              <div class="message-avatar">
                <el-avatar :size="36" style="background-color: #409eff">
                  <el-icon><Cpu /></el-icon>
                </el-avatar>
              </div>
              <div class="message-content">
                <div class="typing-indicator">
                  <span></span>
                  <span></span>
                  <span></span>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 输入区域 -->
        <div class="chat-input-area">
          <el-input
            v-model="inputQuestion"
            type="textarea"
            :rows="3"
            placeholder="请输入您的问题..."
            @keydown.ctrl.enter="handleSend"
            :disabled="isLoading"
          />
          <div class="input-actions">
            <div class="input-tips">
              <el-icon><InfoFilled /></el-icon>
              <span>Ctrl + Enter 发送</span>
            </div>
            <el-button
              type="primary"
              @click="handleSend"
              :loading="isLoading"
              :disabled="!inputQuestion.trim()"
            >
              发送
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, nextTick } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus,
  Delete,
  ChatDotRound,
  User,
  Cpu,
  InfoFilled
} from '@element-plus/icons-vue'
import BossHeader from '@/components/BossHeader.vue'
import axios from 'axios'
import MarkdownIt from 'markdown-it'
import DOMPurify from 'dompurify'

// 初始化 Markdown 解析器
const md = new MarkdownIt({
  html: true,        // 允许HTML标签
  linkify: true,     // 自动转换URL为链接
  typographer: true, // 启用智能引号和其他排版优化
  breaks: true       // 转换换行符为<br>
})

// 数据状态
const historyList = ref([])
const messages = ref([])
const inputQuestion = ref('')
const isLoading = ref(false)
const currentSessionId = ref(null)
const chatMessagesRef = ref(null)

// 快速问题
const quickQuestions = ref([
  '什么是Vue.js的响应式原理？',
  '如何优化前端性能？',
  'Python与Java的区别是什么？',
  '医疗行业的数据隐私如何保护？'
])

// 创建新会话
const createNewSession = () => {
  currentSessionId.value = null
  messages.value = []
  inputQuestion.value = ''
}

// 选择历史记录
const selectHistory = (item) => {
  currentSessionId.value = item.id
  messages.value = [
    {
      question: item.question,
      answer: item.answer,
      timestamp: item.created_at
    }
  ]
  scrollToBottom()
}

// 删除历史记录
const deleteHistory = async (id) => {
  try {
    await ElMessageBox.confirm('确定要删除这条记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    // 从列表中移除（前端本地管理）
    historyList.value = historyList.value.filter(item => item.id !== id)
    
    // 保存到localStorage
    saveHistoryToLocal()
    
    // 如果删除的是当前会话，清空消息
    if (currentSessionId.value === id) {
      createNewSession()
    }
    
    ElMessage.success('删除成功')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('取消删除:', error)
    }
  }
}

// 快速提问
const askQuestion = (question) => {
  inputQuestion.value = question
  handleSend()
}

// 发送问题
const handleSend = async () => {
  if (!inputQuestion.value.trim() || isLoading.value) return

  const question = inputQuestion.value.trim()
  
  // 添加用户问题到消息列表
  messages.value.push({
    question: question,
    answer: '',
    timestamp: new Date().toISOString()
  })

  // 清空输入框
  inputQuestion.value = ''
  isLoading.value = true

  // 滚动到底部
  scrollToBottom()

  try {
    // 调用单轮问答API
    const response = await axios.post('http://localhost:8000/qa/single/', {
      question: question
    })

    // 判断请求是否成功 (code === 1 表示成功)
    if (response.data.code === 1) {
      const answer = response.data.data
      
      // 更新最后一条消息的答案
      messages.value[messages.value.length - 1].answer = answer
      
      // 添加到历史记录列表（前端本地管理）
      const newHistory = {
        id: Date.now(), // 使用时间戳作为临时ID
        question: question,
        answer: answer,
        created_at: new Date().toISOString()
      }
      historyList.value.unshift(newHistory)
      
      // 保存到localStorage
      saveHistoryToLocal()
      
      scrollToBottom()
    } else {
      ElMessage.error(response.data.message || '获取回答失败')
      messages.value[messages.value.length - 1].answer = '抱歉，获取回答时出错了'
    }
  } catch (error) {
    console.error('发送问题失败:', error)
    ElMessage.error('网络错误，请稍后重试')
    messages.value[messages.value.length - 1].answer = '网络连接失败，请检查网络后重试'
  } finally {
    isLoading.value = false
    scrollToBottom()
  }
}

// 获取历史记录（从localStorage加载）
const fetchHistory = async () => {
  try {
    // 从localStorage读取历史记录
    const savedHistory = localStorage.getItem('qa_history')
    if (savedHistory) {
      historyList.value = JSON.parse(savedHistory)
    }
  } catch (error) {
    console.error('获取历史记录失败:', error)
    historyList.value = []
  }
}

// 保存历史记录到localStorage
const saveHistoryToLocal = () => {
  try {
    localStorage.setItem('qa_history', JSON.stringify(historyList.value))
  } catch (error) {
    console.error('保存历史记录失败:', error)
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  if (!timeStr) return ''
  const date = new Date(timeStr)
  const now = new Date()
  const diff = now - date

  // 小于1分钟
  if (diff < 60000) {
    return '刚刚'
  }
  // 小于1小时
  if (diff < 3600000) {
    return `${Math.floor(diff / 60000)}分钟前`
  }
  // 小于24小时
  if (diff < 86400000) {
    return `${Math.floor(diff / 3600000)}小时前`
  }
  // 超过24小时
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  
  return `${year}-${month}-${day} ${hours}:${minutes}`
}

// 格式化答案（支持markdown和HTML）
const formatAnswer = (answer) => {
  if (!answer) return ''
  
  try {
    // 1. 使用 markdown-it 解析 Markdown
    let html = md.render(answer)
    
    // 2. 使用 DOMPurify 清理HTML，防止XSS攻击
    const cleanHtml = DOMPurify.sanitize(html, {
      ALLOWED_TAGS: [
        'p', 'br', 'strong', 'em', 'u', 'del', 's',
        'h1', 'h2', 'h3', 'h4', 'h5', 'h6',
        'ul', 'ol', 'li',
        'blockquote', 'pre', 'code',
        'a', 'img',
        'table', 'thead', 'tbody', 'tr', 'th', 'td',
        'div', 'span'
      ],
      ALLOWED_ATTR: ['href', 'src', 'alt', 'title', 'class', 'id', 'target', 'rel']
    })
    
    return cleanHtml
  } catch (error) {
    console.error('格式化答案失败:', error)
    // 如果解析失败，返回纯文本，但转义特殊字符
    return answer
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/\n/g, '<br>')
  }
}

// 滚动到底部
const scrollToBottom = () => {
  nextTick(() => {
    if (chatMessagesRef.value) {
      chatMessagesRef.value.scrollTop = chatMessagesRef.value.scrollHeight
    }
  })
}

// 页面加载时获取历史记录
onMounted(() => {
  fetchHistory()
})
</script>

<style scoped>
.smart-qa-container {
  min-height: 100vh;
  background: #f5f7fa;
  display: flex;
  flex-direction: column;
}

.qa-main-content {
  flex: 1;
  display: flex;
  padding-top: 60px; /* BossHeader高度 */
  height: calc(100vh - 60px);
}

/* 左侧历史记录 */
.qa-sidebar {
  width: 300px;
  background: #fff;
  border-right: 1px solid #e4e7ed;
  display: flex;
  flex-direction: column;
}

.sidebar-header {
  padding: 20px;
  border-bottom: 1px solid #e4e7ed;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.sidebar-header h3 {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.history-list {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
}

.history-item {
  padding: 12px;
  margin-bottom: 8px;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  border: 1px solid #e4e7ed;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.history-item:hover {
  background: #f5f7fa;
  border-color: #409eff;
}

.history-item.active {
  background: #ecf5ff;
  border-color: #409eff;
}

.history-content {
  flex: 1;
  min-width: 0;
}

.history-question {
  font-size: 14px;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  margin-bottom: 4px;
}

.history-time {
  font-size: 12px;
  color: #909399;
}

.delete-icon {
  color: #f56c6c;
  cursor: pointer;
  opacity: 0;
  transition: opacity 0.3s;
}

.history-item:hover .delete-icon {
  opacity: 1;
}

.empty-history {
  padding: 40px 20px;
  text-align: center;
}

/* 右侧对话区域 */
.qa-chat-area {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: #fff;
}

.chat-messages {
  flex: 1;
  overflow-y: auto;
  padding: 20px;
}

/* 欢迎消息 */
.welcome-message {
  text-align: center;
  padding: 60px 20px;
}

.welcome-icon {
  color: #409eff;
  margin-bottom: 20px;
}

.welcome-message h2 {
  font-size: 28px;
  font-weight: 600;
  color: #303133;
  margin-bottom: 10px;
}

.welcome-message p {
  font-size: 16px;
  color: #606266;
  margin-bottom: 30px;
}

.quick-questions {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 12px;
  max-width: 800px;
  margin: 0 auto;
}

.quick-question-item {
  padding: 16px;
  background: #f5f7fa;
  border: 1px solid #e4e7ed;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s;
  font-size: 14px;
  color: #606266;
}

.quick-question-item:hover {
  background: #ecf5ff;
  border-color: #409eff;
  color: #409eff;
  transform: translateY(-2px);
  box-shadow: 0 2px 12px rgba(64, 158, 255, 0.2);
}

/* 消息样式 */
.message-wrapper {
  margin-bottom: 20px;
}

.message {
  display: flex;
  gap: 12px;
  margin-bottom: 16px;
}

.user-message {
  flex-direction: row-reverse;
}

.message-avatar {
  flex-shrink: 0;
}

.message-content {
  max-width: 70%;
  min-width: 100px;
}

.user-message .message-content {
  background: #409eff;
  color: #fff;
  border-radius: 12px 12px 0 12px;
  padding: 12px 16px;
}

.ai-message .message-content {
  background: #f5f7fa;
  border-radius: 12px 12px 12px 0;
  padding: 12px 16px;
}

.message-text {
  font-size: 14px;
  line-height: 1.6;
  word-wrap: break-word;
}

.message-time {
  font-size: 12px;
  color: #909399;
  margin-top: 8px;
}

/* 输入加载动画 */
.typing-indicator {
  display: flex;
  gap: 4px;
  padding: 8px 0;
}

.typing-indicator span {
  width: 8px;
  height: 8px;
  background: #409eff;
  border-radius: 50%;
  animation: typing 1.4s infinite;
}

.typing-indicator span:nth-child(2) {
  animation-delay: 0.2s;
}

.typing-indicator span:nth-child(3) {
  animation-delay: 0.4s;
}

@keyframes typing {
  0%, 60%, 100% {
    transform: translateY(0);
  }
  30% {
    transform: translateY(-10px);
  }
}

/* 输入区域 */
.chat-input-area {
  border-top: 1px solid #e4e7ed;
  padding: 20px;
  background: #fff;
}

.input-actions {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 12px;
}

.input-tips {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 12px;
  color: #909399;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .qa-main-content {
    flex-direction: column;
  }

  .qa-sidebar {
    width: 100%;
    max-height: 200px;
  }

  .message-content {
    max-width: 85%;
  }

  .quick-questions {
    grid-template-columns: 1fr;
  }
}

/* 滚动条样式 */
.history-list::-webkit-scrollbar,
.chat-messages::-webkit-scrollbar {
  width: 6px;
}

.history-list::-webkit-scrollbar-track,
.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
}

.history-list::-webkit-scrollbar-thumb,
.chat-messages::-webkit-scrollbar-thumb {
  background: #ddd;
  border-radius: 3px;
}

.history-list::-webkit-scrollbar-thumb:hover,
.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #bbb;
}

/* ==================== Markdown 渲染样式 ==================== */

/* 段落 */
:deep(p) {
  margin: 0.8em 0;
  line-height: 1.6;
}

/* 标题 */
:deep(h1), :deep(h2), :deep(h3), :deep(h4), :deep(h5), :deep(h6) {
  margin: 1.2em 0 0.6em 0;
  font-weight: 600;
  line-height: 1.4;
  color: #303133;
}

:deep(h1) { font-size: 1.8em; border-bottom: 2px solid #e4e7ed; padding-bottom: 0.3em; }
:deep(h2) { font-size: 1.5em; border-bottom: 1px solid #e4e7ed; padding-bottom: 0.3em; }
:deep(h3) { font-size: 1.3em; }
:deep(h4) { font-size: 1.1em; }
:deep(h5) { font-size: 1em; }
:deep(h6) { font-size: 0.9em; color: #606266; }

/* 文本格式 */
:deep(strong), :deep(b) {
  font-weight: 600;
  color: #303133;
}

:deep(em), :deep(i) {
  font-style: italic;
  color: #606266;
}

:deep(del), :deep(s) {
  text-decoration: line-through;
  color: #909399;
}

:deep(u) {
  text-decoration: underline;
}

/* 行内代码 */
:deep(code) {
  background: #f5f7fa;
  padding: 2px 6px;
  border-radius: 3px;
  font-family: 'Courier New', 'Consolas', 'Monaco', monospace;
  font-size: 0.9em;
  color: #e74c3c;
  border: 1px solid #e4e7ed;
}

/* 代码块 */
:deep(pre) {
  background: #282c34;
  color: #abb2bf;
  padding: 16px;
  border-radius: 8px;
  overflow-x: auto;
  margin: 1em 0;
  border: 1px solid #3e4451;
}

:deep(pre code) {
  background: transparent;
  padding: 0;
  border: none;
  color: inherit;
  font-size: 0.95em;
  line-height: 1.5;
}

/* 引用块 */
:deep(blockquote) {
  margin: 1em 0;
  padding: 12px 20px;
  border-left: 4px solid #409eff;
  background: #f4f4f5;
  color: #606266;
  border-radius: 0 4px 4px 0;
}

:deep(blockquote p) {
  margin: 0.5em 0;
}

/* 列表 */
:deep(ul), :deep(ol) {
  margin: 0.8em 0;
  padding-left: 2em;
  line-height: 1.8;
}

:deep(ul) {
  list-style-type: disc;
}

:deep(ol) {
  list-style-type: decimal;
}

:deep(li) {
  margin: 0.3em 0;
}

:deep(li > ul), :deep(li > ol) {
  margin: 0.3em 0;
}

/* 嵌套列表 */
:deep(ul ul) {
  list-style-type: circle;
}

:deep(ul ul ul) {
  list-style-type: square;
}

/* 链接 */
:deep(a) {
  color: #409eff;
  text-decoration: none;
  border-bottom: 1px solid transparent;
  transition: all 0.3s;
}

:deep(a:hover) {
  color: #66b1ff;
  border-bottom-color: #66b1ff;
}

/* 图片 */
:deep(img) {
  max-width: 100%;
  height: auto;
  border-radius: 8px;
  margin: 1em 0;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

/* 表格 */
:deep(table) {
  width: 100%;
  border-collapse: collapse;
  margin: 1em 0;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  overflow: hidden;
}

:deep(th), :deep(td) {
  padding: 12px 16px;
  text-align: left;
  border: 1px solid #e4e7ed;
}

:deep(th) {
  background: #f5f7fa;
  font-weight: 600;
  color: #303133;
}

:deep(tr:nth-child(even)) {
  background: #fafafa;
}

:deep(tr:hover) {
  background: #f5f7fa;
}

/* 水平线 */
:deep(hr) {
  border: none;
  border-top: 1px solid #e4e7ed;
  margin: 1.5em 0;
}

/* 针对AI消息的特殊样式 */
.ai-message .message-text {
  font-size: 14px;
  line-height: 1.7;
}

/* 首行不需要上边距 */
.ai-message .message-text :deep(:first-child) {
  margin-top: 0;
}

/* 末行不需要下边距 */
.ai-message .message-text :deep(:last-child) {
  margin-bottom: 0;
}
</style>

